package com.joint.web.action.mp;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.util.LogUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.joint.base.bean.SystemConfig;
import com.joint.base.entity.FileManage;
import com.joint.base.mp.WxMpInCacheConfigStorage;
import com.joint.base.util.StringUtils;
import com.joint.base.util.security.NetWork;
import com.joint.core.entity.Knowledge;
import com.joint.core.service.KnowledgeService;
import com.joint.web.action.BaseController;
import com.mongodb.gridfs.GridFSDBFile;
import net.sf.json.JSONObject;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.ws.rs.PathParam;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * Created by dqf on 2015/3/11.
 */
@Controller
@RequestMapping(value = "/mp")
public class AjaxKnowledgeAction extends BaseController {
    @Resource
    private KnowledgeService knowledgeService;
    @Resource
    private WxMpInCacheConfigStorage wxMpInCacheConfigStorage;
    @Resource
    private SystemConfig systemConfig;

    protected static final CloseableHttpClient httpclient = HttpClients.createDefault();


    private Knowledge knowledge;
    private List<Knowledge> knowledgeList;
    private String searchString;
    private String gridId;
    private String fileUrl;
    private String urlData;
    //文件后缀名
    private String prefix;
    //配置类型
    private String configType;

    @RequestMapping(value = "/ajax-knowledge/list/{searchString}", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> list(int page,String pageKeyword,@PathParam("searchString") String searchString)
    {
        JSONObject data=new JSONObject();
        List<Map<String,Object>>  dataRows= Lists.newArrayList();
        Map<String,Object> rmap;
        pager = new Pager();
        pager.setPageSize(10);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);
        Map<String, Object> map;
        if (StringUtils.isNotEmpty(searchString)){
            map = Maps.newHashMap();
            map.put("state", new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable});
            map.put("name", pageKeyword);
            pager = knowledgeService.findByPagerAndCompany(pager,null,usersService.getCompanyByUser(),map);
        }
        else{
            pager = knowledgeService.findByPagerAndCompany(pager,null,usersService.getCompanyByUser(),new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable});
        }
        knowledgeList = (List<Knowledge>) pager.getList();

        for(Knowledge knowledge:knowledgeList){
            rmap=Maps.newHashMap();
            rmap.put("url",getPath()+"mp/ajax-knowledge/read/"+knowledge.getId());
            rmap.put("superType",knowledge.getSuperType().getName());
            rmap.put("subType",knowledge.getSubType().getName());
            rmap.put("name",knowledge.getName());
            dataRows.add(rmap);
        }
        data.put("pageNum", pager.getPageNumber());//页数
        data.put("pageSize", dataRows.size());//记录数
        data.put("pageCount", pager.getPageCount());//总页数
        data.put("totalCount", pager.getTotalCount());//总记录数
        data.put("pageKeyword", pager.getKeyword()==null?"": pager.getKeyword());//查询
        data.put("dataRows", dataRows);//数据
        return ajaxHtmlAppResult(1, "", JSONObject.fromObject(data));
    }

    /*
    public String read1(){
        if(StringUtils.isEmpty(keyId)) return "index";
        knowledge = knowledgeService.get(keyId);
        String url = wxMpInCacheConfigStorage.getHttpHost() + "/" + systemConfig.getWebroot()+"/com/file!readDoc.action?keyId="+knowledge.getKnowledgeId();
        fileUrl = "http://officeweb365.com/o/?i="+systemConfig.getOfficeId()+"&furl="+url;
        LogUtil.info("{fileUrl}"+fileUrl);
        urlData =  NetWork.getUrlData(fileUrl);
        System.out.println(urlData);
        urlData =  urlData.replaceAll("\\.\\.\\/", "http://officeweb365.com/n/");
        return "read";
    }*/


    public String read(){
        if(StringUtils.isEmpty(keyId)) return "index";
        String[] readType = new String[]{"pdf","doc","docx","xls", "xlsx"};
        knowledge = knowledgeService.get(keyId);
        String knowledgeId = knowledge.getKnowledgeId();
        if(StringUtils.isEmpty(knowledgeId)){
            urlData = "fail";
        }else{
            FileManage fm = fileManageService.get(knowledgeId);
            if(fm!=null){
                String gridId = fm.getGridId();
                GridFSDBFile file =gridFSGet(gridId);
                if(file!=null){
                    String fileName = file.getFilename();
                    prefix = fileName.substring(fileName.lastIndexOf(".")+1);
                    if(!Arrays.asList(readType).contains(prefix)){
                        urlData = "error";
                    }else{
                        configType =systemConfig.getType();
                        String url = wxMpInCacheConfigStorage.getHttpHost() + "/" + systemConfig.getWebroot() + "/com/file!readDoc.action?keyId=" + knowledgeId;
                        if(configType.equals("2")){
                            fileUrl = "http://api.idocv.com/view/url?url=" + url;
                        }else if(configType.equals("3")){

                            fileUrl = "http://test02.9joint.com/JacobPdf/WFileToPdf?domain="+ wxMpInCacheConfigStorage.getHost()+"&gridId=" + gridId;
                        }else {
                            fileUrl = "http://officeweb365.com/o/?i=" + systemConfig.getOfficeId() + "&furl=" + url;
                            LogUtil.info("{fileUrl}" + fileUrl);
                            urlData = NetWork.getUrlData(fileUrl);
                            //  System.out.println(urlData);
                            if (prefix.equals("pdf")) {
                                urlData = urlData.replaceAll("\\.\\.\\/", "http://officeweb365.com/n/");
                                urlData = urlData.replaceAll("GetNextPage\\/", "web365.action");
                                urlData = urlData.replaceFirst("GetPageIndex", "GetPageIndex");
                            }
                        }
                    }
                }
            }
        }

        return "read";
    }
    /**
     * 获取在线doc文件
     * 发送http请求--》获取到数据---》输出到页面
     * @return
     */
    public String loadFile() {
        String result = "";
        if(StringUtils.isEmpty(keyId)) return "index";
        knowledge = knowledgeService.get(keyId);
        String url = wxMpInCacheConfigStorage.getHttpHost() + "/" + systemConfig.getWebroot()+"/com/file!readDoc.action?keyId="+knowledge.getKnowledgeId();
        fileUrl = "http://officeweb365.com/o/?i="+systemConfig.getOfficeId()+"&furl="+url;
        LogUtil.info("FileUrl:"+fileUrl);
        BufferedReader in = null;

        try{
            URL realUrl = new URL(fileUrl);
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            connection.connect();
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }

            LogUtil.info(" {loadFile} " + line);
        }catch(Exception  e){

        }

        return "";
    }

    public Knowledge getKnowledge() {
        return knowledge;
    }

    public void setKnowledge(Knowledge knowledge) {
        this.knowledge = knowledge;
    }

    public List<Knowledge> getKnowledgeList() {
        return knowledgeList;
    }

    public void setKnowledgeList(List<Knowledge> knowledgeList) {
        this.knowledgeList = knowledgeList;
    }

    public String getSearchString() {
        return searchString;
    }

    public void setSearchString(String searchString) {
        this.searchString = searchString;
    }

    public String getGridId() {
        return gridId;
    }

    public void setGridId(String gridId) {
        this.gridId = gridId;
    }

    public String getFileUrl() {
        return fileUrl;
    }

    public void setFileUrl(String fileUrl) {
        this.fileUrl = fileUrl;
    }

    public void setUrlData(String urlData) {
        this.urlData = urlData;
    }
    public String getUrlData() {
        return urlData;
    }
    public String getPrefix() {
        return prefix;
    }

    public void setPrefix(String prefix) {
        this.prefix = prefix;
    }
    public void setConfigType(String configType) {
        this.configType = configType;
    }

    public String getConfigType() {
        return configType;
    }
}
